package net.kleinhenz.questor.ui;

import java.io.FileNotFoundException;
import java.io.IOException;

import net.kleinhenz.questor.Questor;
import net.kleinhenz.questor.system.QSRFile;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;

public class QSRContentProvider extends ContentProvider {

	public static final String BASE_URI = "content://net.kleinhenz.questor.qsr";
	public static final int BASE_URI_LEN = BASE_URI.length();

	@Override
    public String getType(Uri uri) {
        // If the mimetype is not appended to the uri, then return an empty string
        String mimetype = uri.getQuery();
        return mimetype == null ? "" : mimetype;
    }

    @Override
    public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
        if (!"r".equals(mode)) {
            throw new FileNotFoundException("Bad mode for " + uri + ": " + mode);
        }

        QSRFile qsr = null;
        if (Questor.getCurrentGame()!=null)
        	qsr = Questor.getCurrentGame().getCurrentQSR();
        else 
        	// loading screen
        	qsr = Questor.getCurrentLoadQSR();
        	
        String filename = uri.toString().substring(BASE_URI_LEN);

        ParcelFileDescriptor parcel = null;
        try
		{
			parcel = ParcelFileDescriptor.open(qsr.getFile(filename), ParcelFileDescriptor.MODE_READ_ONLY);
		}
		catch (IOException e)
		{
			throw new FileNotFoundException("File not found in QSR: " + filename + ". " + e.getMessage());
		}
		
		return parcel;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean onCreate() {
        return true;
    }
    
    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        throw new UnsupportedOperationException();
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {
        throw new UnsupportedOperationException();
    }
}
